<template>
  <view class="container">
    <view v-if="!isLoaded"></view>
    <view v-else class="details" style="padding: 20rpx 40rpx; padding-bottom: 90px">
      <form class="l-form">
        <view class="l-form-item">
          <view class="l-lbl">加料分组：</view>
          <picker :disabled="disabled" class="form-item-right" style="flex: 1" @change="bindPicker1Change" v-model="details.feedTypeId" :range="tabMenus" :range-key="'name'">
            <view class="uni-input">{{ tabMenus == null ? '无' : tabMenus.find((item) => item.id == details.feedTypeId).name }}</view>
          </picker>
        </view>

        <view class="l-form-item" label="做法标签" name="name">
          <view class="l-lbl required">加料名称:</view>
          <view class="l-form-right l-form-input">
            <input @blur="onBlurEvent($event)" id="name" :disabled="disabled" class="form-item-right" type="text" v-model="details.name" />
          </view>
        </view>

        <view class="l-form-item" label="价格" name="price">
          <view class="l-lbl required">加料价格:</view>
          <view class="l-form-right l-form-input">
            <input @blur="onBlurEvent($event)" id="price" type="digit" :disabled="disabled" placeholder="请输入加料价格~~" class="form-item-right" v-model="details.price" />
          </view>
        </view>
        <!-- 出品部门 -->
        <view class="l-form-item" label="出品部门" name="departId">
          <view class="l-lbl">出品部门：</view>
          <picker
            :disabled="disabled"
            class="form-item-right"
            style="flex: 1"
            @change="bindPickerDepartChange"
            v-model="details.departId"
            :range="departmentList"
            :range-key="'name'"
          >
            <view class="uni-input">
              {{
                details.departId > 0
                  ? departmentList.find((item) => item.id == details.departId) == null
                    ? '无'
                    : departmentList.find((item) => item.id == details.departId).name
                  : '无'
              }}
            </view>
          </picker>
        </view>
        <view class="l-form-item" label="价格" name="purPrice">
          <view class="l-lbl">预估成本:</view>
          <view class="l-form-right l-form-input">
            <input id="purPrice" @blur="onBlurEvent($event)" :disabled="disabled" class="form-item-right" type="digit" v-model="details.purPrice" />
          </view>
        </view>
        <!-- 数字助记码 -->
        <view class="l-form-item" label="数字助记码" name="helpCode">
          <view class="l-lbl required">数字助记码:</view>
          <view class="l-form-right l-form-input">
            <input id="helpCode" @blur="onBlurEvent($event)" :disabled="disabled" class="form-item-right" type="text" v-model="details.helpCode" />
          </view>
        </view>
        <!-- 保质期 -->
        <view class="l-form-item" label="保质期" name="warrantyDate">
          <view class="l-lbl required">保质期:</view>
          <view class="l-form-right l-form-input">
            <input id="warrantyDate" @blur="onBlurEvent($event)" :disabled="disabled" class="form-item-right" type="text" v-model="details.warrantyDate" />
          </view>
        </view>

        <!-- 保质期单位 -->
        <view class="l-form-item" label="保质期单位" name="warrantyType">
          <view class="l-lbl">保质期单位:</view>
          <picker
            :disabled="disabled"
            class="form-item-right"
            style="flex: 1"
            @change="bindPickerwarrantyTypeChange"
            v-model="details.warrantyType"
            :range="warrantyTypeEnum"
            :range-key="'name'"
          >
            <view class="uni-input">{{ warrantyTypeEnum.find((item) => item.value == details.warrantyType).name }}</view>
          </picker>
        </view>

        <!-- 拼音助记码 -->
        <view class="l-form-item" label="拼音助记码" name="pinYin">
          <view class="l-lbl required">拼音助记码:</view>
          <view class="l-form-right l-form-input">
            <input @blur="onBlurEvent($event)" id="pinYin" :disabled="disabled" class="form-item-right" type="text" v-model="details.pinYin" />
          </view>
        </view>
        <!-- 条形码 -->
        <view class="l-form-item" label="条形码" name="code">
          <view class="l-lbl required">条形码:</view>
          <view class="l-form-right l-form-input">
            <input id="code" @blur="onBlurEvent($event)" :disabled="disabled" class="form-item-right" type="text" v-model="details.code" />
          </view>
        </view>
        <!-- 是否需要打印 -->
        <view class="l-form-item" label="是否需要打印" name="isPrint">
          <view class="l-lbl" style="width: 200rpx">是否需要打印:</view>
          <!-- <radio-group :disabled="disabled" class="form-item-right" name="isPrint" @change="radioIsPrintChange">
            <label style="margin-right: 30rpx">
              <radio :disabled="disabled" :value="true" :checked="details.isPrint" />
              <text>是</text>
            </label>
            <label>
              <radio :disabled="disabled" :value="false" :checked="!details.isPrint" />
              <text>否</text>
            </label>
          </radio-group> -->
          <u-radio-group iconSize="14" v-model="details.isPrint">
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginTop: '12rpx' }" label="是" :name="1"></u-radio>
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginLeft: '8px', marginTop: '12rpx' }" label="否" :name="0"></u-radio>
          </u-radio-group>
        </view>

        <!-- 收银端临时改价 -->
        <view class="l-form-item" label="收银端临时改价" name="changePrice">
          <view class="l-lbl" style="width: 200rpx">收银端临时改价:</view>
          <!-- <radio-group :disabled="disabled" class="form-item-right" name="changePrice" @change="radioChangePrice">
            <label style="margin-right: 30rpx">
              <radio :disabled="disabled" :value="true" :checked="details.changePrice" />
              <text>是</text>
            </label>
            <label>
              <radio :disabled="disabled" :value="false" :checked="!details.changePrice" />
              <text>否</text>
            </label>
          </radio-group> -->
          <u-radio-group iconSize="14" v-model="details.changePrice">
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginTop: '12rpx' }" label="是" :name="1"></u-radio>
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginLeft: '8px', marginTop: '12rpx' }" label="否" :name="0"></u-radio>
          </u-radio-group>
        </view>

        <!-- 收银端手动打折 -->
        <view class="l-form-item" label="收银端手动打折" name="discounts">
          <view class="l-lbl" style="width: 200rpx">收银端手动打折:</view>
          <!-- <radio-group :disabled="disabled" class="form-item-right" name="discounts" @change="radioDiscountsChange">
            <label style="margin-right: 30rpx">
              <radio :disabled="disabled" :value="true" :checked="details.discounts" />
              <text>是</text>
            </label>
            <label>
              <radio :disabled="disabled" :value="false" :checked="!details.discounts" />
              <text>否</text>
            </label>
          </radio-group> -->
          <u-radio-group iconSize="14" v-model="details.discounts">
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginTop: '12rpx' }" label="是" :name="1"></u-radio>
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginLeft: '8px', marginTop: '12rpx' }" label="否" :name="0"></u-radio>
          </u-radio-group>
        </view>
        <!-- 售卖状态 -->
        <view class="l-form-item" label="售卖状态" name="status">
          <view class="l-lbl">售卖状态:</view>
          <picker :disabled="disabled" class="form-item-right" style="flex: 1" @change="bindPickerstatusChange" v-model="details.status" :range="statusEnum" :range-key="'name'">
            <view class="uni-input">{{ statusEnum.find((item) => item.value == details.status).name }}</view>
          </picker>
        </view>

        <view class="l-form-item" label="是否通用" name="currencyFlag">
          <view class="l-lbl">是否通用:</view>
          <!-- <radio-group
            :disabled="disabled"
            class="form-item-right"
            name="currencyFlag"
            @change="radioCurrencyFlagChange"
          >
            <label style="margin-right: 30rpx">
              <radio
                :disabled="disabled"
                :value="1"
                :checked="details.currencyFlag == 1"
              />
              <text>是</text>
            </label>
            <label>
              <radio
                :disabled="disabled"
                :value="0"
                :checked="details.currencyFlag !== 1"
              />
              <text>否</text>
            </label>
          </radio-group> -->
          <u-radio-group v-model="details.currencyFlag">
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginTop: '12rpx' }" label="是" :name="1"></u-radio>
            <u-radio size="20" activeColor="#edac2f" :customStyle="{ marginLeft: '8px', marginTop: '12rpx' }" label="否" :name="0"></u-radio>
          </u-radio-group>
        </view>
      </form>

      <view v-if="mode == 'add'" class="btn-group" style="position: fixed; left: 0; right: 0; bottom: 0; height: 70px; background-color: #fff">
        <view
          @click="btnAddClick"
          style="
            display: flex;
            align-items: center;
            justify-content: center;
            height: 49px;
            font-size: 18px;
            width: 100%;
            background-color: #f3c45d;
            color: #fff;
            border-radius: 10px;
            padding: 0 10px;
            margin-bottom: 10px;
            margin-left: 10px;
            margin-right: 10px;
          "
          size="mini"
        >
          添加
        </view>
      </view>
      <!-- 编辑模式 -->
      <view v-else class="btn-group" style="display: flex; align-items: center; position: fixed; left: 15rpx; right: 15rpx; bottom: 0; height: 80px; background-color: #fff">
        <view
          @click="btnDelClick"
          style="
            display: flex;
            flex: 1;
            margin-right: 15px;
            align-items: center;
            justify-content: center;
            height: 49px;
            font-size: 18px;
            background-color: #f56c6c;
            letter-spacing: 3px;
            color: #fff;
            font-weight: bold;
            border-radius: 10px;
          "
          size="mini"
        >
          删除
        </view>
        <view
          @click="btnEditClick"
          style="
            display: flex;
            flex: 1;
            margin-left: 15px;
            align-items: center;
            justify-content: center;
            height: 49px;
            font-size: 18px;
            background-color: #f3c45d;
            letter-spacing: 3px;
            color: #fff;
            font-weight: bold;
            border-radius: 10px;
          "
          size="mini"
        >
          保存
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import { ref, reactive, onMounted, toRefs, getCurrentInstance } from '@vue/composition-api';
import { corpId, storeId } from '../../../constants/apiConstants';
import { uShowLoading, uHideLoading, uNavigateTo, umodal, utoast, uSetNavigationBarTitle } from '../../../utils/uniUtils.js';
import { onLoad } from '@dcloudio/uni-app';
import { toastIconEnum } from '../../../constants/uiConstants';
import checker from '../../../common/graceChecker';
import { transfer, transferTypeEnum } from '../../../common/dataTransfer.js';
import { checkerType, modeEnum } from '../../../constants/normalConstants.js';
export default {
  name: 'addFeed',
  setup(props) {
    // 生命周期
    onMounted(async () => {
      try {
        uShowLoading();
        if (data.mode == 'edit') {
          console.log('edit');
          const result = await GetFoodFeedEdit(data.id);
          data.details = result.data;
        } else {
          console.log('add');

          data.details = {
            corpId: corpId,
            storeId: storeId,
            feedTypeId: 0,
            name: '',
            price: 0.0,
            purPrice: 0.0,
            departId: 0,
            helpCode: '',
            pinYin: '',
            warrantyDate: 0,
            warrantyType: 0,
            code: '',
            isPrint: 1,
            changePrice: 1,
            discounts: 1,
            status: 1,
            image: '',
            isDelete: false,
            currencyFlag: 1,
            createTime: '2023-10-30 18:27:35',
            updateTime: '2024-01-11 17:17:01',
            modifyTime: 0,
            number: 0,
            foodCount: 2,
            isSelected: false,
            isExclusive: false
          };
        }

        data.details.departId = data.details.departId == null ? 0 : data.details.departId;
        await GetFoodFeedCategory();
        await GetDepartment();
        uHideLoading();
      } catch (error) {
        uHideLoading();
      } finally {
        data.isLoaded = true;
      }
    });
    onLoad(async (options) => {
      data.id = options.id;
      data.mode = options.mode == 'edit' ? 'edit' : 'add';
      uSetNavigationBarTitle((options.mode == 'edit' ? '编辑' : '新增') + '加料');

      if (data.mode == 'edit') {
        data.id = options.id;
      }
    });

    const { proxy } = getCurrentInstance();
    // 数据定义
    const data = reactive({
      mode: 'add', // 模式
      isLoaded: false,
      id: 0,
      tabMenus: null,
      departmentList: [], // 部门列表
      statusEnum: [
        //   售卖状态枚举
        { name: '在售', value: 1 },
        { name: '停售', value: 2 },
        { name: '定时起停售', value: 3 }
      ],
      warrantyTypeEnum: [
        // 保质期单位枚举
        { name: '天', value: 0 },
        { name: '年', value: 1 },
        { name: '月', value: 2 },
        { name: '小时', value: 3 },
        { name: '分钟', value: 4 }
      ],
      currentCateIdx: 0, //左边默认分类
      details: {}, //   加料详情
      disabled: false, // 禁用
      lock: false, // 节流锁

      // 数据转换器
      transferRules: [
        {
          name: 'name',
          type: transferTypeEnum.trim
        },
        {
          name: 'price',
          type: transferTypeEnum.float
        },
        {
          name: 'purPrice',
          type: transferTypeEnum.floatOrNull
        },
        {
          name: 'warrantyDate',
          type: transferTypeEnum.int
        },
        {
          name: 'helpCode',
          type: transferTypeEnum.trim
        },
        {
          name: 'pinYin',
          type: transferTypeEnum.trim
        },
        {
          name: 'code',
          type: transferTypeEnum.trim
        }
      ],
      //表单校验规则
      rules: [
        {
          name: 'name',
          checkType: checkerType.endNotNull,
          errorMsg: '名称不能为空~~'
        },
        {
          name: 'code',
          checkType: checkerType.endNotNull,
          errorMsg: '条形码不能为空~~'
        },
        {
          name: 'pinYin',
          checkType: checkerType.endNotNull,
          errorMsg: '拼音助记码不能为空~~'
        },
        {
          name: 'helpCode',
          checkType: checkerType.endNotNull,
          errorMsg: '数字助记码不能为空~~'
        }
      ]
    });

    const onBlurEvent = (e) => {
      console.log('e', e);
      // console.log("e-->", e.mp.target.id);
      const name = e.currentTarget.id; // 获取输入框的id
      // 数据转换
      transfer(data.details, data.transferRules);
      // console.log(name, this.form[name]);

      // 表单校验
      if (name != null) {
        let rules = [];
        const rule = data.rules.find((item) => item.name == name);
        // console.log("name", name);
        // console.log("rules", this.rules);
        // console.log("rule", rule);
        // console.log("rule!=null", rule != null);

        if (rule != null) {
          rules.push(rule);
          const isOk = checker.check(data.details, rules);
          // console.log("isOk", isOk);

          if (!isOk) {
            utoast(checker.error, toastIconEnum.none);
          }
        }
      }
    };

    // 获取加料
    function GetFoodFeedEdit(id) {
      return proxy.$api.GetFoodFeedEdit({ id });
    }

    /**
     * 获取加料分类
     */
    const GetFoodFeedCategory = async () => {
      console.log('获取加料分类~~');
      let {
        data: { list }
      } = await proxy.$api.GetFoodFeedCategory({
        pageNum: 1,
        pageSize: 9999
      });
      console.log('list-->', list);
      data.tabMenus = list;
      if (data.mode == 'add' && data.tabMenus.length > 0) {
        data.details.feedTypeId = data.tabMenus[0].id;
      } else {
        utoast('加料分组为空！');
      }
    };

    const bindPicker1Change = (e) => {
      // console.log("e-->", e);
      data.details.feedTypeId = data.tabMenus[e.detail.value].id;
    };

    const bindPickerwarrantyTypeChange = (e) => {
      // console.log("e-->", e);
      data.details.warrantyType = data.warrantyTypeEnum[e.detail.value].value;
    };

    const bindPickerstatusChange = (e) => {
      // console.log("e-->", e);
      data.details.status = data.statusEnum[e.detail.value].value;
    };

    const bindPicker2Change = (e) => {
      // console.log("e-->", e);
      data.details.addPriceWay = data.addPriceWayList[e.detail.value].id;
    };

    /**
     *  上tab栏 点击事件
     */
    const onTabClick = async (e) => {
      await this.GetFoodFeed(e.index);
      data.currentCateIdx = 0;
      data.disabled = true;
    };

    /**
     * 做法分组选择事件
     */
    const feedCataChange = (e) => {
      console.log(e);
    };

    /**
     * 添加按钮点击事件
     */
    const btnAddClick = async () => {
      data.details.name = data.details.name.trim();
      console.log(data.details);
      transfer(data.details, data.transferRules);
      // 表单校验
      let isOk = checker.check(data.details, data.rules);
      if (!isOk) {
        await utoast(checker.error, toastIconEnum.none);
        return;
      }

      /*    if (data.details.name.length == 0) {
        utoast("加料名称为空！", "error");
        return;
      }

      if (data.details.price == null || data.details.price.length == 0) {
        utoast("价格为空！", "error");
        return;
      }
 */
      if (data.lock == true) {
        return;
      }

      data.lock = true;
      const res = await proxy.$api.AddFoodFeed(data.details);
      if (res?.code == 0) {
        utoast('操作成功');
        setTimeout(() => {
          uni.hideToast();
          uni.navigateTo({
            url: '/pages/workbench/feed/list'
          });
          data.lock = false;
        }, 2000);
      }
      setTimeout(() => {
        data.lock = false;
        console.log('fail', data.lock);
      }, 2000);
    };

    /**
     * 获取部门列表
     */
    const GetDepartment = async () => {
      let {
        data: { list }
      } = await proxy.$api.GetDepartment({
        pageNum: 1,
        pageSize: 9999
      });
      console.log('部门列表-->', list);
      data.departmentList = [
        {
          id: 0,
          name: '无'
        },
        ...list
      ];
    };

    const bindPickerDepartChange = (e) => {
      data.details.departId = data.departmentList[e.detail.value].id;
    };

    function radioIsPrintChange(e) {
      data.details.isPrint = e.detail.value;
    }
    function radioChangePrice(e) {
      data.details.changePrice = e.detail.value;
    }
    function radioDiscountsChange(e) {
      data.details.discounts = e.detail.value;
    }
    function radioCurrencyFlagChange(e) {
      data.details.currencyFlag = e.detail.value;
    }

    async function btnDelClick() {
      const res = await umodal();
      // 确定删除
      if (res) {
        const result = await proxy.$api.DelFoodFeed({
          id: data.details.id
        });
        console.log(result);
        if (result.code != null && result.code == 0) {
          await utoast('删除成功！', toastIconEnum.success);
          data.disabled = true;
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/workbench/feed/list'
            });
          }, 1000);
        } else {
          await utoast('删除失败！', toastIconEnum.error);
        }
      }
    }

    /**
     * `编辑`按钮点击事件
     * @param item
     */
    async function btnEditClick() {
      console.log('提交表单', data.details);
      if (!(await umodal('确认要提交吗？'))) {
        return;
      }
      transfer(data.details, data.transferRules);

      // 表单校验
      let isOk = checker.check(data.details, data.rules);
      if (!isOk) {
        await utoast(checker.error, toastIconEnum.none);
        return;
      }

      /*   data.details.name = data.details.name.trim();

      if (data.details.name.length == 0) {
        await utoast("名称为空!", "error");
        return;
      }
 */
      const res = await proxy.$api.EditFoodFeed(data.details);
      if (res?.code == 0) {
        await utoast('操作成功');
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/workbench/feed/list'
          });
        }, 1000);
      } else {
        setTimeout(() => {
          console.log('fail', data.lock);
        }, 2000);
      }
    }

    return {
      ...toRefs(data),
      bindPicker1Change,
      bindPickerstatusChange,
      bindPickerwarrantyTypeChange,
      btnAddClick,
      bindPickerDepartChange,
      radioIsPrintChange,
      radioChangePrice,
      radioDiscountsChange,
      radioCurrencyFlagChange,
      btnDelClick,
      btnEditClick,
      onBlurEvent
    };
  }
};
</script>

<style lang="scss" scoped>
@import '~@/static/styles/commonStyle.scss';

.container {
  .details {
    background-color: #fff;

    .form-item {
      display: flex;
      align-items: center;
      padding: 14rpx 0;

      .lbl {
        width: 80px;
        font-size: 14px;
      }

      .form-item-right {
        flex: 1;
      }
    }
  }

  .btn-group {
    display: flex;
    justify-content: space-around;
    padding-top: 22rpx;
  }

  picker {
    flex: 1;
    border: 1px solid #cacaca;
    background-color: #fff;
    padding: 7rpx 10rpx;
    border-radius: 5px;
    position: relative;
  }
}
</style>
